package com.fqgame.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fqgame.user.entity.UserOrder;
import com.fqgame.user.service.UserOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 订单控制器
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private UserOrderService userOrderService;

    /**
     * 获取订单详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<UserOrder> getOrderDetail(@PathVariable Long id) {
        log.info("获取订单详情，订单ID：{}", id);
        UserOrder order = userOrderService.getById(id);
        if (order == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(order);
    }

    /**
     * 获取用户订单列表
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Page<UserOrder>> getUserOrders(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        log.info("获取用户订单列表，用户ID：{}，页码：{}，每页大小：{}", userId, page, size);
        
        Page<UserOrder> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<UserOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserOrder::getUserId, userId)
                .orderByDesc(UserOrder::getCreateTime);
        
        Page<UserOrder> result = userOrderService.page(pageParam, queryWrapper);
        return ResponseEntity.ok(result);
    }

    /**
     * 支付订单
     */
    @PostMapping("/{id}/pay")
    public ResponseEntity<Map<String, Object>> payOrder(@PathVariable Long id) {
        log.info("支付订单，订单ID：{}", id);
        
        try {
            boolean success = userOrderService.payOrder(id);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", success);
            result.put("message", success ? "订单支付成功" : "订单支付失败");
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("订单支付失败", e);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", e.getMessage());
            
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 手动触发超时订单取消（任务调度示例）
     */
    @PostMapping("/cancel-timeout")
    public ResponseEntity<Map<String, Object>> cancelTimeoutOrders() {
        log.info("手动触发超时订单取消");
        
        try {
            userOrderService.cancelTimeoutOrders();
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "超时订单取消已触发");
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("超时订单取消触发失败", e);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", e.getMessage());
            
            return ResponseEntity.badRequest().body(result);
        }
    }
}